#!/usr/bin/env python
# -*- coding: utf-8 -*-

import web
import hashlib
from config import settings
from controllers.pool import *
from message import *
from controllers.log import mylog
from controllers.room import RoomMgt

#玩家池
cache = Pool()
roommgt = RoomMgt()

render = settings.render

def getIDbyName(s):
    m = hashlib.md5()
    m.update(s)
    return m.hexdigest()
    
class Login:

    def GET(self):
        #online = cache.GetOnlineName()
        return render.login()

    def POST(self):
        '''
            -1:no room
            -2:invalid user
        '''
        i = web.input()
        print '>>>>>>>>>>>>>>>>>>'
        print i
        data   = i.keys()[0]
        name   = data.split(',')[0]
        gender = data.split(',')[1]
        roomid = data.split(',')[2]
        mylog.info('Request Login:name(%s),gender(%s),roomid(%s)'%(name,gender,roomid))

        #取房间
        proom = roommgt.GetRoombyRoomId(roomid)
        if not proom:
            mylog.error('Get Room:roomid(%s) error!'%(roomid))
            return '-1:没有找到房间,请重新选择房间.'
        #检查房间里是否有该用户
        id = getIDbyName(name)
        ret = proom.cache.GetObj(id)
        if ret:
            mylog.error('Username(%s) is already exsists!'%(name))
            return '-2:对不起,用户已存在,请重新输入用户名'
        else:
            mylog.info('Username(%s) is not find, can enter room!'%(name))
            #这里接受通过验证的用户名并创建用户，页面跳转在ajax的响应里做
            ret = proom.Login(name,gender)
            if ret:
                ret = -1
            else:
                ret = 0
            mylog.info('Login room():ret=(%d)'%(ret))
            return '1:nothing'
            

#ajax 获取服务器上的房间信息
class GetRoomInfo():
    
    def GET(self):
        data = ''
        for item in roommgt.config:
            data += item.roomname+",%d;"%int(item.roomid)
        #print msg
        return data

    
class Chat:

    def GET(self):
        return render.chat()

    def POST(self):
        pass


class Update():
    
    def GET(self,data):
        print '******************************************'
        print data
        p = data.split('/')
        if len(p) != 2:
            mylog.error('Param Loss!')
            return ""
        roomid = p[0]
        usrname = p[1]
        #取房间，找到该房间的玩家，取出待接受的所有消息
        proom = roommgt.GetRoombyRoomId(roomid)
        if not proom:
            print 'error'
            mylog.error('Not find room:Username(%s),roomid(%s)'%(usrname,roomid))
            return ""
        player = proom.cache.GetObj(id)
        if not player:
            print 'error'
            mylog.error('Target player not found:Username(%s),roomid(%s)'%(usrname,roomid))
            return ""
        #取出对列中的消息
        print 'i reiceived'
        return "[{time:1,usr:'chenbin',msg:'Helloafd'},]"

    def POST(self):
        
        i = web.input()      
        msg = ''
        for item in i.keys():
            msg += item
        PackMsg(msg)

class GetOnlineUsr:

    def GET(self,roomid):
        #print '>>>>>>'
        #print roomid
        proom = roommgt.GetRoombyRoomId(roomid)
        if not proom:
            mylog.error('Not find room:Username(%s),roomid(%s)'%(usrname,roomid))
            return "-1"
        onlinelist = proom.GetList()

        #test
        #onlinelist.append(('chenbin','1'))        
        msg = "["
        for item in onlinelist:
            name,gender = item
            print '>>>>'
            print name,gender
            msg +="{name:'%s',gender:'%s'},"%(name,gender)
        msg += "]"

        print msg
        return msg
        
class Logout():

    def POST(self):
        i = web.input()
        data = i.keys()[0]
        data   = i.keys()[0]
        name   = data.split(',')[0]
        gender = data.split(',')[1]
        roomid = data.split(',')[2]
        print 'roomid:%s'%roomid
        #get room
        proom = roommgt.GetRoombyRoomId(roomid)
        if not proom:
            mylog.error('Room not found:UsrName(%s),Gender(%s),RoomId(%s)'%(name,gender,roomid))
            return
        proom.Logout(name)
        mylog.info('Player Logout:UsrName(%s),Gender(%s),RoomId(%s)'%(name,gender,roomid));
